<?php
require_once 'class.Page.php';

class Article extends Page
{
    protected function _parse_parameters ()
    {
		$match = preg_match('%/(\d{4})/(\d{2})/(.+?)\.html%',G::uri(),$m);
		if (!$match) G::p404('no this article');
		list($drop, $year, $month, $aid) = $m;
		$datafile = _ROOT . _DS . 'etc' . _DS . 'db' . _DS . _CHANNEL . _DS . $year . $month . '.db';
		if (!file_exists($datafile)) G::p404('article database '.$datafile.' not exists');
		$this->db = new PDO('sqlite:' . $datafile);
		//$this->datadb = new PDO('sqlite:' . $datadir . 'tag.db');
        $this->page = substr($this->uri, 1);
		$this->tpl = G::tpl();
		$this->aid = $aid;
    }

    protected function _index ()
    {
		if (!$this->aid) die('Need aid.');
		$sql = "SELECT * FROM summary JOIN detail on detail.id=summary.id WHERE summary.id=?";
		$st = $this->db->prepare($sql);
		$st->execute(array($this->aid));
		$article = $st->fetch(PDO::FETCH_ASSOC);
		if (!$article) die('No this article');
		if ($article['deleted']) die('Article has been removed');
        $this->tpl->assign('title', $this->_charTransfer($article['title']));
        $this->tpl->assign('summary', $this->_charTransfer($article['summary']));
		$this->tpl->assign('body', gzuncompress($article['data']));
        $this->tpl->display(_TPL.'article/article.html');
	}

	protected function _charTransfer ($s, $to='GB2312')
	{
		$enc = mb_detect_encoding($s);
		if (substr(strtolower($enc),0,2)=='gb') return $s;
		$r = iconv($enc, $to.'//TRANSLIT//IGNORE', $s);
		return $r;
	}
}